package co.infinum.goldfinger.example;

import co.infinum.goldfinger.Goldfinger;
import co.infinum.goldfinger.example.widget.ProgressDialog;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;

/**
 * ex.
 *
 * @author zh
 * @since 2021-06-25
 */
public abstract class BasePaymentAbility extends Ability {
    private ProgressDialog dialog;
    private Component paymentButton;
    private Text userResultView;
    protected Ability context;

    protected abstract void authenticateUser();

    protected abstract void initGoldfinger();

    protected void handleGoldfingerResult(Goldfinger.Result result) {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                dialog.hide();
                userResultView.setVisibility(Component.VISIBLE);
                if (result.type() == Goldfinger.Type.SUCCESS || result.type() == Goldfinger.Type.ERROR) {
                    String formattedResult = String.format("%s - %s", result.type().toString(), result.message());
                    userResultView.setText(formattedResult);
                }
            }
        });
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_payment);
        context = this;
        initGoldfinger();
        initViews();
        initListeners();
    }

    @Override
    protected void onActive() {
        super.onActive();
        userResultView.setVisibility(Component.HIDE);
    }

    private void initListeners() {
        paymentButton.setClickedListener(v -> {
            userResultView.setVisibility(Component.HIDE);
            showDialog();
            authenticateUser();
        });
    }

    private void initViews() {
        paymentButton = findComponentById(ResourceTable.Id_paymentButton);
        userResultView = (Text) findComponentById(ResourceTable.Id_userResultView);
    }

    protected void showError(Throwable e) {
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                dialog.hide();
                userResultView.setVisibility(Component.VISIBLE);
                userResultView.setText(e.getMessage());
            }
        });
    }

    private void showDialog() {
        dialog = new ProgressDialog(this);
        dialog.show();
    }
}
